<template>
  <div class="container">
    <div class="radioBtns">
      <div class="header">系统设置</div>
      <el-divider />
      <el-checkbox
        class="checkboxItem"
        v-model="systemLimitSet.isSign"
        label="每日重置签到"
      />
      <el-checkbox
        class="checkboxItem"
        v-model="systemLimitSet.isTask"
        label="每日生成任务表"
      />
      <el-checkbox
        class="checkboxItem"
        v-model="systemLimitSet.isDaily"
        label="每日发送日报"
        @change="isDailyChange"
      />
      <el-checkbox
        class="checkboxItem"
        v-model="systemLimitSet.isApiEdit"
        label="记录API访问信息"
      />
      <el-checkbox
        class="checkboxItem"
        v-model="systemLimitSet.isRemoteLogin"
        label="账号是否允许多处登陆"
      />
      <el-form
        ref="modelForm"
        :model="systemLimitSet"
        :rules="rules"
        :inline="true"
      >
        <el-form-item label="token加密密钥设置" prop="tokenSecretKey">
          <el-input
            v-model="systemLimitSet.tokenSecretKey"
            placeholder="请输入"
            style="width: 320px"
          >
          </el-input>
        </el-form-item>
        <el-form-item label="数据加密密钥设置" prop="dataSecretKey">
          <el-input
            v-model="systemLimitSet.dataSecretKey"
            disabled
            placeholder="请输入"
            style="width: 320px"
          >
          </el-input>
        </el-form-item>
        <el-form-item label="token有效期" prop="tokenExpireTime">
          <el-input
            v-model.number="systemLimitSet.tokenExpireTime"
            placeholder="请输入"
            style="width: 150px"
          >
            <template #append>分钟</template>
          </el-input>
        </el-form-item>
        <el-form-item
          :required="systemLimitSet.isDaily"
          prop="DailySendTime"
          label="发送日报时间"
        >
          <el-time-select
            v-model="systemLimitSet.DailySendTime"
            start="00:00"
            step="00:15"
            end="23:45"
            format="HH:mm:ss"
            placeholder="请选择发送时间"
          />
        </el-form-item>
      </el-form>
      <div class="reservedAccount">
        <el-button link type="success">预留账号</el-button>
        <el-divider style="width: 200px; margin: 16px 0px" />
        <div class="list">
          <el-tag
            v-for="item in systemLimitSet.reservedAccount"
            :key="item"
            closable
            type="success"
            style="margin: 10px 16px 10px 0px"
            :disable-transitions="false"
            @close="handleTagClose(item)"
          >
            {{ item }}
          </el-tag>
          <el-input
            v-if="tagInputVisible"
            ref="InputRef"
            v-model="tagInputvalue"
            style="width: 100px"
            @keyup.enter="handleInputConfirm"
            @blur="handleInputConfirm"
          />
          <el-button
            v-else
            class="button-new-tag"
            color="rgb(240,249,235)"
            style="color: #95d475"
            @click="showInput"
          >
            + 添加
          </el-button>
        </div>
      </div>
      <div class="action">
        <el-button class="btn" color="#d9ecff" @click="handleSystemSetUpdate"
          >更 新 设 置</el-button
        >
      </div>
    </div>
    <div class="radioBtns">
      <div class="header">表数据操作</div>
      <el-divider />
      <BaseRadioGroup v-model="selectRadio" :option="dataSheetOption">
      </BaseRadioGroup>
      <div class="action">
        <el-button class="btn" color="#d9ecff" @click="handleClick"
          >确 定</el-button
        >
      </div>
    </div>
  </div>
</template>

<script setup lang="ts" name="adminSetting">
import { ref, onMounted } from "vue";
import type { FormInstance } from "element-plus";
import { BaseRadioGroup } from "@components/BaseForm/index";
import {
  ElMessage as message,
  ElNotification as NOT,
  ElMessageBox as messageBox,
} from "element-plus";
import { postAction } from "@api/request";
import * as api from "@/api/index";
interface optionRadioType {
  label: string;
  hint: string;
  coreVal: number | string;
  coreApi: string;
  disabled: boolean;
}
// 系统设置
let systemLimitSet: any = ref({});
// 预留账号输入框控制器
let tagInputVisible = ref(false);
// 预留账号输入框内容
let tagInputvalue = ref("");
// form表单实例
let modelForm = ref<any>();
let rules = {
  tokenExpireTime: [
    { required: true, message: "token有效期不能为空" },
    {
      validator: (rule: any, value: any, callback: Function) => {
        if (value > 240) {
          return callback(new Error("token有效期不能超过8小时"));
        }
        if (value < 30) {
          return callback(new Error("token有效期不能小于30分钟"));
        }
        callback();
      },
    },
  ],
  tokenSecretKey: [
    { required: true, message: "token有效期不能为空" },
    {
      validator: (rule: any, value: any, callback: Function) => {
        if (value.length !== 32) {
          return callback(new Error("请输入32位加密密钥"));
        } else {
          callback();
        }
      },
    },
  ],
  dataSecretKey: [
    { required: true, message: "token有效期不能为空" },
    {
      validator: (rule: any, value: any, callback: Function) => {
        if (value.length !== 32) {
          callback(new Error("请输入32位加密密钥"));
        } else {
          callback();
        }
      },
    },
  ],
  DailySendTime: [
    {
      validator: (rule: any, value: any, callback: Function) => {
        if (systemLimitSet.value.isDaily && !value) {
          return callback(new Error("请选择每天发送日报时间"));
        } else {
          callback();
        }
      },
    },
  ],
};

let selectRadio = ref("");

const handleTagClose = (item: string) => {
  messageBox
    .confirm(
      `确定移除 ${item} 账号的预留资格吗？将在更新设置之后生效！`,
      "温馨提示",
      {
        confirmButtonText: "确认",
        cancelButtonText: "取消",
        type: "warning",
        draggable: true,
      }
    )
    .then(() => {
      let i = systemLimitSet.value.reservedAccount.indexOf(item);
      systemLimitSet.value.reservedAccount.splice(i, 1);
    });
};

const showInput = () => {
  tagInputVisible.value = true;
};

// 确认添加预留账号
const handleInputConfirm = () => {
  if (tagInputvalue.value) {
    if (systemLimitSet.value.reservedAccount.includes(tagInputvalue.value)) {
      message.warning("该预留账号已存在");
    } else {
      systemLimitSet.value.reservedAccount.push(tagInputvalue.value);
    }
  }
  tagInputVisible.value = false;
  tagInputvalue.value = "";
};

let dataSheetOption: optionRadioType[] = [
  {
    label: "清空用户数据",
    hint: "此操作将清空数据库内所有用户、将导致用户无法登陆！",
    coreVal: 1,
    coreApi: "/note/admin-delete-drop",
    disabled: false,
  },
  {
    label: "清空操作数据",
    hint: "此操作将清空数据库内所有操作记录、操作后将无法查看任何操作日志",
    coreVal: 4,
    coreApi: "/note/admin-delete-drop",
    disabled: false,
  },
  {
    label: "清空文档数据",
    hint: "此操作将清空数据库内所有文档",
    coreVal: 3,
    coreApi: "/note/admin-delete-drop",
    disabled: false,
  },
  {
    label: "清空进度数据",
    hint: "此操作将清空数据库内所有进度数据、操作后将无法查看进行中/已完成/待完成的任务进度",
    coreVal: 2,
    coreApi: "/note/admin-delete-drop",
    disabled: false,
  },
  {
    label: "清空自动任务数据",
    hint: "此操作将清空系统自动产生的任务数据、操作后将无法查看包括但不限于签到/日报等完成情况",
    coreVal: 5,
    coreApi: "/note/admin-delete-drop",
    disabled: false,
  },
  {
    label: "清空API访问记录",
    hint: "此操作将清空系统记录的API访问数据、操作后将无法查看API的访问情况",
    coreVal: 6,
    coreApi: "/note/admin-delete-drop",
    disabled: false,
  },
  {
    label: "清空上传资源表",
    hint: "此操作将清空所有用户上传的文件数据、操作后将无法访问资源",
    coreVal: 7,
    coreApi: "/note/admin-delete-drop",
    disabled: false,
  },
];

onMounted(() => {
  getSystemSet();
});
let changeRadio = (val: number) => {};

// 每日日报开关变更
let isDailyChange = () => {
  // 开关清除日报时间的校验信息
  modelForm.value?.clearValidate(["DailySendTime"]);
};

// 数据表操作
let handleClick = () => {
  if (selectRadio.value) {
    let items = dataSheetOption.filter((item: optionRadioType) => {
      return item.coreVal === selectRadio.value;
    })[0];
    if (items) {
      messageBox
        .confirm(items.hint, `${items.label}提示`, {
          confirmButtonText: "确认",
          cancelButtonText: "取消",
          type: "warning",
          draggable: true,
        })
        .then(() => {
          postAction(items.coreApi, { type: items.coreVal }).then(
            (res: BaseResponse<boolean>) => {
              if (res.body) {
                message.success("命令操作成功！");
              }
            }
          );
        })
        .catch(() => {});
    } else {
      message.warning("遇到意料之外的错误");
    }
  } else {
    message.warning("请选择要执行的操作！");
  }
};

// 更新用户设置
let handleUserSetUpdate = () => {
  message.warning("功能开发中、敬请期待！");
};

// 获取系统设置
let getSystemSet = () => {
  api.admin.getSystem({}).then((res: BaseResponse<any>) => {
    if (res.header.code === 999) {
      systemLimitSet.value = res.body;
    }
  });
};

// 更新系统设置
let handleSystemSetUpdate = () => {
  modelForm.value?.validate((valid: boolean) => {
    console.log(valid);
    if (valid) {
      api.admin
        .systemSet(systemLimitSet.value)
        .then((res: BaseResponse<boolean>) => {
          if (res.header.code === 999) {
            message.success(res.header.message || "系统设置更新成功！");
          }
        });
    }
  });
};
</script>

<style lang="less" scoped>
.container {
  display: flex;
  flex-direction: column;
  justify-content: flex-start;
  align-items: center;
  .radioBtns {
    width: 94%;
    padding: 24px;
    // min-height: 200px;
    margin-bottom: 24px;
    background-color: aliceblue;
    .header {
      font-size: 16px;
      font-weight: 700px;
    }
    .action {
      text-align: right;
      .btn {
        width: 100%;
        height: 40px;
      }
    }
    .reservedAccount {
      margin-bottom: 16px;
    }
    .checkBox {
      display: flex;
      flex-wrap: wrap;
      margin-bottom: 18px;
      .checkboxItem {
        width: 30%;
      }
    }
  }
}
</style>
